package com.blb.day3;

import java.util.concurrent.*;

public class ThreadPoolTest {

    public static void main(String[] args) {
//        testNewCachedThreadPool();
//        testNewFixedThreadPool();
//        testNewSingleThreadPool();
//        testNewScheduledThreadPool();
        testMyThreadPool();
    }

    private static void testNewCachedThreadPool() {
        //创建不限的线程池
        ExecutorService threadPool = Executors.newCachedThreadPool();
        //执行线程
        for (int i = 0;i < 10;i++){
            threadPool.execute(() -> {
                System.out.println(Thread.currentThread().getName()+"执行了");
            });
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //关闭线程池
        threadPool.shutdown();
    }

    private static void testNewFixedThreadPool() {
        //创建长度固定的线程池
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        //执行线程
        for (int i = 0;i < 100;i++){
            threadPool.execute(() -> {
                System.out.println(Thread.currentThread().getName()+"执行了");
            });
        }
        //关闭线程池
        threadPool.shutdown();
    }

    private static void testNewSingleThreadPool() {
        //创建单线程的线程池
        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        //执行线程
        for (int i = 0;i < 100;i++){
            threadPool.execute(() -> {
                System.out.println(Thread.currentThread().getName()+"执行了");
            });
        }
        //关闭线程池
        threadPool.shutdown();
    }

    private static void testNewScheduledThreadPool() {
        //创建可调度的线程池
        ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(10);
        //延迟2秒，每隔1秒执行线程
        threadPool.scheduleAtFixedRate(() -> {
            System.out.println(Thread.currentThread().getName()+"执行了");
        },2,1, TimeUnit.SECONDS);
    }

    private static void testMyThreadPool(){
        int cpuNum = Runtime.getRuntime().availableProcessors();
        System.out.println("cpu:" + cpuNum);
        int n = 2;
        ThreadPoolExecutor pool = new ThreadPoolExecutor(cpuNum * n, cpuNum * n,
                0L, TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>());
        //执行线程
        for (int i = 0;i < 100;i++){
            pool.execute(() -> {
                System.out.println(Thread.currentThread().getName()+"执行了");
            });
        }
        //关闭线程池
        pool.shutdown();
    }
}
